package com.example.sbbsec;

import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.hash.Hashing;

import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newTreeSet;

/**
 * <p> 微信支付生成签名工具类
 *
 * @author lowe.yang on 2018-09-04
 */
public final class WxSignUtil {

    private WxSignUtil() {
    }

    private static final String SIGN_PATTERN = "{0}&key={1}";


    /**
     * 构造微信支付签名
     *
     * @param params 请求加密参数
     * @return 加密签名
     */
    public static String createSign(Map<String, Object> params, String signKey) {
        //去除map中的空值,键值按照字段顺序排序(TreeSet默认自然排序)
        final TreeSet<String> keys = newTreeSet();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (entry.getValue() != null) {
                keys.add(entry.getKey());
            }
        }
        final List<String> coupleList = newArrayList();

        for(String key :keys){
                coupleList.add(key + "=" + params.get(key).toString());
        }

        final String signStr = Joiner.on("&").join(coupleList);

        //拼接秘钥
        final String sign = MessageFormat.format(SIGN_PATTERN, signStr, signKey);
        //MD5 加密
        return Hashing.md5().newHasher().putString(sign,Charsets.UTF_8).hash().toString().toUpperCase();
    }
}
